/*
 * Copyright 2017 Baiyyy
 * @(#)DeviceController.java
 */

package com.byyy.ccts.modules.cc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.byyy.ccts.core.common.controller.BaseCRUDController;
import com.byyy.ccts.core.model.AjaxJson;
import com.byyy.ccts.core.model.PageJson;
import com.byyy.ccts.core.query.data.PropertyPreFilterable;
import com.byyy.ccts.core.query.data.Queryable;
import com.byyy.ccts.core.query.utils.QueryableConvertUtils;
import com.byyy.ccts.core.query.wrapper.EntityWrapper;
import com.byyy.ccts.core.security.shiro.authz.annotation.RequiresPathPermission;
import com.byyy.ccts.core.utils.DateUtils;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.core.utils.excel.ExcelExportUtil;
import com.byyy.ccts.core.utils.excel.entity.ExcelTitle;
import com.byyy.ccts.core.utils.pdf.PDFReport;
import com.byyy.ccts.modules.cc.Global;
import com.byyy.ccts.modules.cc.entity.ccts.TADevice;
import com.byyy.ccts.modules.cc.entity.ccts.TSHumiture;
import com.byyy.ccts.modules.cc.mapper.HumitureMapper;
import com.byyy.ccts.modules.cc.service.IDeviceService;
import com.byyy.ccts.modules.cc.service.IHumitureService;
import com.byyy.ccts.modules.sys.Constants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 设备信息
 * Created by DELL on 2018-5-14.
 */
@Controller
@RequestMapping("${admin.url.prefix}/cc/device/humiture")
@RequiresPathPermission("sys:user")
public class HumitureController extends BaseCRUDController<TSHumiture, String> {

    @Autowired
    private IHumitureService humitureService;

    @Autowired
    private IDeviceService deviceService;

    @Override
    public void preList(Model model, HttpServletRequest request, HttpServletResponse response) {
        String sn = request.getParameter("sn");
        String carFlag = request.getParameter("carFlag");
        String pointone = request.getParameter("pointone");
        String pointtwo = request.getParameter("pointtwo");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        String wendMin = request.getParameter("wendMin");
        String wendMax = request.getParameter("wendMax");
        if ("1".equals(carFlag)) {
            model.addAttribute("sn", pointone + "," + pointtwo);
        }
        else {
            model.addAttribute("sn", sn);
        }
        model.addAttribute("beginDate", beginDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("wendMin", wendMin);
        model.addAttribute("wendMax", wendMax);
    }

    @Override
    public void preAjaxList(Queryable queryable, EntityWrapper<TSHumiture> entityWrapper, HttpServletRequest request,
                            HttpServletResponse response) {
    }

    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     *
     * @param request
     * @param response
     * @throws java.io.IOException
     */
    @RequestMapping(value = "humitureAjaxList", method = { RequestMethod.GET, RequestMethod.POST })
    public void humitureAjaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                                HttpServletResponse response) throws IOException {
        EntityWrapper<TSHumiture> entityWrapper = new EntityWrapper<TSHumiture>(TSHumiture.class);
        if (!StringUtils.isEmpty(request.getParameter("sn"))) {
            entityWrapper.in("B.ID", Arrays.asList(request.getParameter("sn").split(",")));
        }
        if (!StringUtils.isEmpty(request.getParameter("beginDate"))
                && !request.getParameter("beginDate").startsWith("undefined")) {
            entityWrapper.ge("COLLECT_TIME", DateUtils.toDate(request.getParameter("beginDate"), "yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(request.getParameter("endDate"))
                && !request.getParameter("endDate").startsWith("undefined")) {
            entityWrapper.le("COLLECT_TIME", DateUtils.toDate(request.getParameter("endDate"), "yyyy-MM-dd HH:mm:ss"));
        }
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, TSHumiture.class);
        SerializeFilter filter = propertyPreFilterable.constructFilter(TSHumiture.class);
        PageJson<TSHumiture> pagejson = new PageJson<TSHumiture>(this.humitureService.humitureList(queryable, entityWrapper));
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    /**
     * 查询设备时间段信息
     *
     * @throws IOException
     */
    @RequestMapping(value = "queryDeviceTempByTime", method = {RequestMethod.GET})
    @ResponseBody
    public AjaxJson queryDeviceTempByTime(String deviceId, Date beginDate, Date endDate){
        AjaxJson ajaxJson = new AjaxJson();
        List<TSHumiture> humitureList = null;
        if (deviceId.split(Global.SPLIT_COMMA).length > 1) {
            List<TADevice> deviceList = this.deviceService.selectBatchIds(Arrays.asList(deviceId.split(Global.SPLIT_COMMA)));
            List<String> snList = new ArrayList<>();
            for (TADevice device : deviceList) {
                snList.add(device.getSn());
            }
            humitureList = this.humitureService.queryDeviceTempByTime(snList, beginDate, endDate);
        }
        else {
            TADevice device = this.deviceService.selectById(deviceId);
            humitureList = this.humitureService.queryDeviceTempByTime(Arrays.asList(device.getSn()), beginDate, endDate);
        }
        ajaxJson.setData(humitureList);
        if (humitureList == null || humitureList.size() < 1) {
            ajaxJson.fail("未能查询到数据");
        }
        return ajaxJson;
    }

    /**
     * 查询设备最新信息
     *
     * @throws IOException
     */
    @RequestMapping(value = "currentInfo", method = {RequestMethod.GET})
    @ResponseBody
    public AjaxJson currentInfo(){
        AjaxJson ajaxJson = new AjaxJson();
        List<TSHumiture> humitureList = this.humitureService.queryCurrentInfo();
        ajaxJson.setData(humitureList);
        if (humitureList == null || humitureList.size() < 1) {
            ajaxJson.fail("未能查询到数据");
        }
        return ajaxJson;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "expExcel")
    public void expExcel(String sn, String collectTime, HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        OutputStream fOut = null;
        HSSFWorkbook workbook = null;

        TADevice device = this.deviceService.selectById(sn);
        Date startTime = null;
        Date endTime = null;
        if (!StringUtils.isEmpty(collectTime)) {
            String[] date = collectTime.split(",");
            if (date != null && date.length > 0) {
                startTime = DateUtils.toDate(date[0], "yyyy-MM-dd HH:mm:ss");
                if (date.length > 1) {
                    endTime = DateUtils.toDate(date[1], "yyyy-MM-dd HH:mm:ss");
                }
            }
        }

        // 预处理
        List<TSHumiture> humitures = this.humitureService.queryDeviceTempByTime(Arrays.asList(device.getSn()), startTime, endTime);

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + this.getResponseFileName(request, "采集设备温度数据") + ".xls");
            // 根据浏览器进行转码，使其支持中文文件名
            ExcelTitle title = new ExcelTitle("采集设备温度数据", "", "采集设备温度数据");
            workbook = ExcelExportUtil.exportExcel(title, TSHumiture.class, humitures);
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "expPDF")
    public void expPDF(String sn, String collectTime, HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        OutputStream fOut = null;
        TADevice device = this.deviceService.selectById(sn);
        Date startTime = null;
        Date endTime = null;
        if (!StringUtils.isEmpty(collectTime)) {
            String[] date = collectTime.split(",");
            if (date != null && date.length > 0) {
                startTime = DateUtils.toDate(date[0], "yyyy-MM-dd HH:mm:ss");
                if (date.length > 1) {
                    endTime = DateUtils.toDate(date[1], "yyyy-MM-dd HH:mm:ss");
                }
            }
        }

        // 预处理
        List<TSHumiture> humitures = this.humitureService.queryDeviceTempByTime(Arrays.asList(device.getSn()), startTime, endTime);

        try {
            fOut = response.getOutputStream();
            response.setDateHeader("Expires",
                    System.currentTimeMillis() + 31536000000L);
            response.setHeader("Cache-Control", "public, max-age=7776000");
                response.setHeader("content-disposition", "attachment;filename="
                        + this.getResponseFileName(request, "采集设备温度数据") + ".pdf");
            // 根据浏览器进行转码，使其支持中文文件名
//            PDFReport.generateHumiturePDF(humitures, fOut);
            PDFReport.exportPDF(fOut, humitures, TSHumiture.class);
        } finally {
            try {
                if (fOut != null) {
                    fOut.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "expAllExcel")
    public void expAllExcel(String collectTime, HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        OutputStream fOut = null;
        HSSFWorkbook workbook = null;

        Date startTime = null;
        Date endTime = null;
        if (!StringUtils.isEmpty(collectTime)) {
            String[] date = collectTime.split(",");
            if (date != null && date.length > 0) {
                startTime = DateUtils.toDate(date[0], "yyyy-MM-dd HH:mm:ss");
                if (date.length > 1) {
                    endTime = DateUtils.toDate(date[1], "yyyy-MM-dd HH:mm:ss");
                }
            }
        }

        // 预处理
        List<TSHumiture> humitures = this.humitureService.queryAllDeviceTempByTime(startTime, endTime);

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + this.getResponseFileName(request, "采集设备温度数据") + ".xls");
            // 根据浏览器进行转码，使其支持中文文件名
            ExcelTitle title = new ExcelTitle("采集设备温度数据", "", "采集设备温度数据");
            workbook = ExcelExportUtil.exportExcel(title, TSHumiture.class, humitures);
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "expAllPDF")
    public void expAllPDF(String collectTime, HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
        OutputStream fOut = null;
        Date startTime = null;
        Date endTime = null;
        if (!StringUtils.isEmpty(collectTime)) {
            String[] date = collectTime.split(",");
            if (date != null && date.length > 0) {
                startTime = DateUtils.toDate(date[0].substring(0, 10) + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                if (date.length > 1) {
                    endTime = DateUtils.toDate(date[1].substring(0, 10) + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                }
            }
        }
        else {
            return;
        }

        // 预处理
        List<TSHumiture> humitures = this.humitureService.queryAllDeviceTempByTime(startTime, endTime);

        try {
            fOut = response.getOutputStream();
            response.setDateHeader("Expires",
                    System.currentTimeMillis() + 31536000000L);
            response.setHeader("Cache-Control", "public, max-age=7776000");
            response.setHeader("content-disposition", "attachment;filename="
                    + this.getResponseFileName(request, "采集设备温度数据"
                    + DateUtils.formatDate(startTime, Global.PATTERN_YYYYMMMDD)
                    + "至"
                    + DateUtils.formatDate(endTime, Global.PATTERN_YYYYMMMDD)) + ".pdf");
            // 根据浏览器进行转码，使其支持中文文件名
//            PDFReport.generateHumiturePDF(humitures, fOut);
            PDFReport.exportPDF(fOut, humitures, TSHumiture.class);
        } finally {
            try {
                if (fOut != null) {
                    fOut.close();
                }
            } catch (IOException e) {
            }
        }
    }
}
